package com.jm.offer.easy;

import com.jm.offer.ListNode;

import java.util.List;

/**
 * @Description https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/
 * @date 2022/4/13 9:00
 */
public class _22链表中倒数第k个节点 {

    public static void main(String[] args) {
        ListNode head = new ListNode(1,new ListNode(2, new ListNode(3,new ListNode(4))));
        ListNode node = getKthFromEnd(head, 2);
        while (node!=null){
            System.out.println(node.val);
            node = node.next;
        }
    }

    public static ListNode getKthFromEnd(ListNode head, int k) {
        if (head == null){
            return head;
        }
        int j = 0;
        ListNode node = head;
        while (node != null){
            j++;
            node = node.next;
        }
        int c = j - k;
        ListNode listNode = head;
        for (int i = 0; i < c; i++) {
            listNode = listNode.next;
        }
        head = listNode;
        return head;
    }
}
